package com.yfqy.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.yfqy.admin.conf.Idgenerator.SnowflakeIdGenerator;
import com.yfqy.admin.constant.MyConstants;
import com.yfqy.admin.domain.dto.product.ProductSkuDTO;
import com.yfqy.admin.domain.dto.promotion.ProductPromotionDTO;
import com.yfqy.admin.domain.dto.promotion.PromotionConfDTO;
import com.yfqy.admin.domain.dto.promotion.PromotionQueryDTO;
import com.yfqy.admin.domain.entity.ProductPromotion;
import com.yfqy.admin.domain.entity.ProductSpu;
import com.yfqy.admin.domain.entity.ProductSpuImages;
import com.yfqy.admin.domain.mapper.ProductPromotionMapper;
import com.yfqy.admin.domain.mapper.ProductSkuMapper;
import com.yfqy.admin.domain.mapper.ProductSpuImagesMapper;
import com.yfqy.admin.domain.mapper.ProductSpuMapper;
import com.yfqy.admin.domain.vo.PromotionVO;
import com.yfqy.admin.security.login.LoginUserInfo;
import com.yfqy.admin.service.ProductPromotionService;
import com.yfqy.admin.transform.UserNameTranslator;
import com.yfqy.admin.util.AuthUserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ProductPromotionServiceImpl implements ProductPromotionService {

    private final SnowflakeIdGenerator idGenerator;
    private final ProductPromotionMapper productPromotionMapper;
    private final ProductSpuMapper productSpuMapper;
    private final ProductSkuMapper productSkuMapper;
    private final ProductSpuImagesMapper productSpuImagesMapper;
    private final UserNameTranslator userNameTranslator;

    @Override
    public boolean createPromotion(ProductPromotionDTO dto) {
        // 校验活动时间
        if (dto.getStartTime().after(dto.getEndTime())) {
            throw new IllegalArgumentException("活动开始时间不能晚于结束时间");
        }

        ProductSpu productSpu = productSpuMapper.selectByPrimaryKey(dto.getSpuid());
        if (Objects.isNull(productSpu) || productSpu.getStatus() == MyConstants.BT2) {
            throw new IllegalArgumentException("商品不存在或已下架，创建活动失败");
        }

        // spu 的 sku列表
        Map<Long, BigDecimal> skuPriceMap = productSkuMapper.selectSkuDTOsBySpuId(dto.getSpuid())
                .stream().collect(Collectors.toMap(ProductSkuDTO::getId, ProductSkuDTO::getPrice));
        if (CollUtil.isNotEmpty(dto.getSkuids())) {
            if (dto.getSkuids().stream().anyMatch(id -> !skuPriceMap.containsKey(Long.valueOf(id)))) {
                throw new IllegalArgumentException("商品SKU不存在或已下架，创建活动失败");
            }

        }
        // 多个sku，使用最小商品价
        BigDecimal minPrice = Collections.min(skuPriceMap.values(), BigDecimal::compareTo);
        dto.setPromotionPrice(minPrice);

        // 校验同商品同时间段是否有冲突活动
        // 检查未开始和进行中的
        if (productPromotionMapper.selectCount(dto) > 0) {
            throw new IllegalArgumentException("该商品在指定时间段内已有促销活动");
        }

        ProductPromotion promotion = BeanUtil.toBean(dto, ProductPromotion.class);
        promotion.setId(idGenerator.nextId());
        promotion.setSkuids(String.join(",", dto.getSkuids()));
        promotion.setCreatedBy(getCurrentUserId());
        promotion.setModifiedBy(promotion.getCreatedBy());
        promotion.setConfig(JSONUtil.toJsonStr(dto.getPromotionConfDTOS()));
        return productPromotionMapper.insertSelective(promotion) > 0;
    }


    @Override
    public boolean updatePromotion(ProductPromotionDTO dto) {
        if (dto.getId() == null) {
            throw new IllegalArgumentException("id不能为空");
        }

        ProductPromotion existing = productPromotionMapper.selectByPrimaryKey(dto.getId());
        if (existing == null) {
            throw new IllegalArgumentException("促销活动不存在");
        }

        // 已开始的活动不允许修改
        if (existing.getStatus() == MyConstants.BT1) {
            throw new IllegalArgumentException("进行中的活动不允许修改");
        }

        // 校验活动时间
        if (dto.getStartTime().after(dto.getEndTime())) {
            throw new IllegalArgumentException("活动开始时间不能晚于结束时间");
        }

        // 更新字段
        ProductPromotion updateEntity = BeanUtil.toBean(dto, ProductPromotion.class);
        updateEntity.setModifiedBy(getCurrentUserId());
        updateEntity.setConfig(JSONUtil.toJsonStr(dto.getPromotionConfDTOS()));
        return productPromotionMapper.updateByPrimaryKeySelective(updateEntity) > 0;
    }

    @Override
    public boolean endPromotion(Long promotionId) {
        ProductPromotion existing = productPromotionMapper.selectByPrimaryKey(promotionId);
        if (existing == null) {
            throw new IllegalArgumentException("促销活动不存在");
        }

        // 已开始的活动不允许删除
        if (existing.getStatus() == MyConstants.BT2) {
            return true;
        }

        // 活动下架不需要考虑商品库存是否被其他线程锁定
        existing.setStatus(MyConstants.BT2);
        existing.setModifiedBy(getCurrentUserId());
        return productPromotionMapper.updateByPrimaryKeySelective(existing) > 0;
    }

    @Override
    public PageInfo<PromotionVO> queryPromotionPage(PromotionQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPageIndex(), queryDTO.getPageSize());
        List<PromotionVO> promotionVOS = productPromotionMapper.queryPromotionPage(queryDTO);
        if (CollUtil.isEmpty(promotionVOS)) {
            return new PageInfo<>(Lists.newArrayList());
        }
        List<Long> spuIds = promotionVOS.stream().map(PromotionVO::getSpuid).toList();
        List<ProductSpu> productSpus = productSpuMapper.selectSpuNameBySpuIds(spuIds);
        List<String> spuDown = productSpus.stream().filter(spu -> spu.getStatus() == MyConstants.BT2).map(ProductSpu::getSpuName).toList();
        if (CollUtil.isNotEmpty(spuDown)) {
            throw new IllegalArgumentException(String.join(",", spuDown) + "已下架，请刷新活动页面");
        }
        List<ProductSpuImages> spuMainImagesList = productSpuImagesMapper.selectMainImagesBySpuIds(spuIds);
        Map<Long, String> spuMainImagesMap = spuMainImagesList.stream().collect(Collectors.toMap(ProductSpuImages::getId, ProductSpuImages::getMainImages));
        Map<Long, String> spuMap = productSpus.stream().collect(Collectors.toMap(ProductSpu::getId, ProductSpu::getSpuName));
        promotionVOS.forEach(vo -> {
            vo.setProductName(spuMap.get(vo.getSpuid()));
            vo.setProductSpuMainImage(spuMainImagesMap.get(vo.getSpuid()).split(",")[0]);
            vo.setPromotionConfDTOS(JSONUtil.toList(vo.getConfig(), PromotionConfDTO.class));
            vo.setConfig("");
        });
        userNameTranslator.translationUser(promotionVOS);
        PageInfo<PromotionVO> pageInfo = new PageInfo<>(promotionVOS);
        PageHelper.clearPage();
        return pageInfo;
    }

    @Override
    public List<PromotionVO> getActivePromotionsBySpuId(Long spuId) {
        return null;
    }

    @Override
    public int endPromotionBySpuId(Long spuId) {
        return productPromotionMapper.endPromotionBySpuId(spuId, getCurrentUserId());
    }


    private Long getCurrentUserId() {
        LoginUserInfo loginUserInfo = AuthUserContext.getLocalAuthUser();
        return Objects.nonNull(loginUserInfo) ? loginUserInfo.getId() : MyConstants._L1;
    }
}
